package com.cys.markdown.doc.admin.controller.sys;

import com.cys.common.data.RespCodeEnum;
import com.cys.common.pojo.RespEntity;
import com.cys.common.util.base.MapUtil;
import com.cys.common.util.base.StringUtil;
import com.cys.common.util.encrypt.MD5;
import com.cys.mid.core.system.data.LockedEnum;
import com.cys.mid.core.system.entity.SysUser;
import com.cys.mid.core.system.interfaces.entity.ISysRole;
import com.cys.mid.core.system.interfaces.entity.ISysUser;
import com.cys.mid.core.system.interfaces.service.SysDeptService;
import com.cys.mid.core.system.interfaces.service.SysRoleService;
import com.cys.mid.core.system.interfaces.service.SysUserService;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 系统用户-控制层
 * Created by caiyushen on 2018/12/23.
 */
@Controller
@RequestMapping("/admin/sys/user")
@Transactional(rollbackFor = Exception.class)
public class UserController {

    private Logger logger = LoggerFactory.getLogger(UserController.class);

    @Resource(name = "sysDeptServiceImpl")
    private SysDeptService sysDeptService;

    @Resource(name = "sysUserServiceImpl")
    private SysUserService sysUserService;

    @Resource(name = "sysRoleServiceImpl")
    private SysRoleService sysRoleService;

    @Value("${sys.user.password.md5.key}")
    protected String sysUserPasswordMd5Key;

    /**
     * 获取人员列表
     *
     * @param pageNo           当前页数
     * @param pageSize         当前页显示的数据量
     * @param params-sysDeptId 部门id
     */
    @RequestMapping(value = "/getList", method = RequestMethod.GET)
    @ResponseBody
    public RespEntity getList(Integer pageNo, Integer pageSize, @RequestParam Map<String, Object> params) {
        logger.info("method[getList] pageNo:" + pageNo + " pageSize:" + pageSize + " params:" + params.toString());
        PageInfo<ISysUser> pageList = sysUserService.findPageUserDept(pageNo, pageSize, params);
        return new RespEntity(RespCodeEnum.success, pageList);
    }

    /**
     * 新增用户
     *
     * @param map 用户数据
     * @author caiyushen
     */
    @ResponseBody
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public RespEntity add(@RequestParam Map map) throws Exception {
        if (!StringUtil.checkObj(map)) {
            logger.error("method[add] map is null.");
            return new RespEntity(RespCodeEnum.deficiency);
        }
        logger.info("method[add] map:" + map.toString());
        ISysUser sysUser = sysUserService.findByAccount(MapUtil.getString(map, "sysUserAccount"));
        if (StringUtil.checkObj(sysUser)) {
            logger.warn("method[save] sysUser is null. map:" + map.toString());
            return new RespEntity(RespCodeEnum.user_repeat);
        }
        map.put("sysUserPassword", MD5.encode(MapUtil.getString(map, "sysUserPassword") + sysUserPasswordMd5Key));
        map.put("loginFailureCount", 0);
        if (!StringUtil.checkObj(map.get("isLocked"))) {
            map.put("isLocked", LockedEnum.unLocked.getValue());
        }
        sysUserService.save(map);
        return new RespEntity(RespCodeEnum.success);
    }

    /**
     * 根据用户id获取信息
     *
     * @param sysUserId 用户信息主键
     */
    @ResponseBody
    @RequestMapping(value = "/find", method = RequestMethod.GET)
    public RespEntity find(Long sysUserId) {
        logger.info("method[find] sysUserId: " + sysUserId);
        ISysUser sysUser = sysUserService.find(sysUserId);
        return new RespEntity(RespCodeEnum.success, sysUser);
    }

    /**
     * 修改用户
     * （无法修改密码）
     *
     * @author caiyushen
     */
    @ResponseBody
    @RequestMapping(value = "/update", method = RequestMethod.PUT)
    public RespEntity update(@RequestParam Map map) throws Exception {
        logger.info("method[update] map: " + map.toString());
        List<ISysUser> sysUserList = sysUserService.findListByAccount(MapUtil.getString(map, "sysUserAccount"));
        if (CollectionUtils.isEmpty(sysUserList)) {
            logger.warn("method[update] sysUser is null. map:" + map.toString());
            return new RespEntity(RespCodeEnum.deficiency);
        }
        if (StringUtil.checkObj(sysUserList) && sysUserList.size() > 1) {
            logger.warn("method[update] sysUserListSize > 1. map:" + map.toString());
            return new RespEntity(RespCodeEnum.user_repeat);
        }
        //修改用户信息不允许修改密码
        map.put("sysUserPassword", null);
        //修改用户信息不允许修改账号
        map.put("sysUserAccount", null);
        sysUserService.updatePart(map);
        return new RespEntity(RespCodeEnum.success);
    }

    /**
     * 重设密码
     *
     * @param sysUserId 用户id
     */
    @ResponseBody
    @RequestMapping(value = "/updatePassword", method = RequestMethod.PUT)
    public RespEntity updatePassword(Long sysUserId) {
        if (!StringUtil.checkObj(sysUserId)) {
            logger.warn("method[updatePassword] 入参缺失。sysUserId:" + sysUserId);
            return new RespEntity(RespCodeEnum.error);
        }
        String sysUserPassword = StringUtil.randomStr(6);
        sysUserService.updatePassword(sysUserId, MD5.encode(sysUserPassword + sysUserPasswordMd5Key));
        return new RespEntity(RespCodeEnum.success, "操作成功，密码：" + sysUserPassword);
    }


    /**
     * 删除用户
     *
     * @param id 用户id
     * @author caiyushen
     */
    @ResponseBody
    @RequestMapping(value = "/delete", method = RequestMethod.DELETE)
    public RespEntity delete(Long id) {
        if (!StringUtil.checkObj(id)) {
            logger.warn("method[delete] id is null.");
            return new RespEntity(RespCodeEnum.deficiency);
        }
        //逻辑删除
        sysUserService.logicDeleteById(id);
        return new RespEntity(RespCodeEnum.success);
    }

    /**
     * 获取角色列表
     */
    @ResponseBody
    @RequestMapping(value = "/getRoleList", method = RequestMethod.GET)
    public RespEntity getRoleList() {
        List<ISysRole> dataList = sysRoleService.findList(new HashMap<>());
        return new RespEntity(RespCodeEnum.success, dataList);
    }

    /**
     * 根据用户id获取用户-角色关联数据
     *
     * @param userId 用户主键
     */
    @ResponseBody
    @RequestMapping(value = "/getRoleByUserId", method = RequestMethod.GET)
    public RespEntity getRoleByUserId(Long userId) {
        if (!StringUtil.checkObj(userId)) {
            logger.error("method[getRoleByUserId] userId is null.");
            return new RespEntity(RespCodeEnum.deficiency);
        }
        List<ISysRole> dataList = sysRoleService.findListByUserId(userId);
        return new RespEntity(RespCodeEnum.success, dataList);
    }

    /**
     * 保存用户-角色关联
     *
     * @param userId 用户id
     * @param roleId 角色id
     */
    @ResponseBody
    @RequestMapping(value = "/saveUserRelRole", method = RequestMethod.POST)
    public RespEntity saveUserRole(Long userId, Long roleId) throws Exception {
        logger.info("method[saveUserRelRole] userId:" + userId + " roleId:" + roleId);
        if (!StringUtil.checkObj(userId)) {
            return new RespEntity(RespCodeEnum.deficiency);
        }
        if (!StringUtil.checkObj(roleId)) {
            return new RespEntity(RespCodeEnum.deficiency);
        }
        sysRoleService.saveRelateUser(roleId, userId);
        return new RespEntity(RespCodeEnum.success);
    }

    /**
     * 解锁用户
     *
     * @param id 用户id
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/unLockBySysUserId", method = RequestMethod.PUT)
    public RespEntity unLockBySysUserId(Long id) {
        if (!StringUtil.checkObj(id)) {
            logger.warn("method[unLockBySysUserId] id is null.");
            return new RespEntity(RespCodeEnum.deficiency);
        }
        ISysUser sysUser = new SysUser();
        sysUser.setSysUserId(id);
        sysUser.setIsLocked(LockedEnum.unLocked.getValue());
        sysUser.setLoginFailureCount(0);
        sysUserService.updatePart(sysUser);
        return new RespEntity(RespCodeEnum.success);
    }


}
